<template>
  <div class="content" v-loading="loading">
    <el-card>
      <div class="header">
        <h3 class="title">{{ contentConfig.header?.title ?? '数据列表' }}</h3>
        <el-button class="add-btn" type="primary" icon="Plus" @click="addDept" v-if="isCreate">
          {{ contentConfig.header?.btnTitle ?? '新建数据' }}
        </el-button>
      </div>

      <div class="table">
        <!-- row-key， tree-props为table展开行需要设置的类型，tree-props可以不写, row-key必填 -->
        <el-table
          ref="elTableRef"
          :data="pageList"
          border
          stripe
          :row-key="contentConfig.childrenTree?.rowKey"
          :tree-props="contentConfig.childrenTree?.treeProps"
        >
          <template v-for="(item, index) in contentConfig.propsList" :key="index">
            <template v-if="item.type === 'index' || item.type === 'selection' || item.type === 'normal'">
              <el-table-column v-bind="item" />
            </template>

            <template v-else-if="item.type === 'timer'">
              <el-table-column v-bind="item">
                <template #default="{ row }">{{ formatUTC(row[item.prop + '']) }}</template>
              </el-table-column>
            </template>

            <template v-else-if="item.type === 'handler'">
              <el-table-column v-bind="item" v-if="isUpdate && isDelete">
                <template #default="{ row }">
                  <el-button size="small" link icon="Edit" type="primary" @click="editTable(row)" v-if="isUpdate">编辑</el-button>
                  <el-button size="small" link icon="Delete" type="danger" @click="removeTable(row)" v-if="isDelete">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </template>

            <template v-else-if="item.type === 'custom'">
              <el-table-column v-bind="item">
                <template #default="{ row }">
                  <slot :name="item.slotName" v-bind="row" :prop="item.prop + ''"></slot>
                </template>
              </el-table-column>
            </template>

            <!-- table展开行 -->
            <template v-else>
              <el-table-column v-bind="item" />
            </template>
          </template>
        </el-table>
      </div>

      <div class="pagination" v-if="contentConfig?.isPagination ?? true">
        <el-pagination
          style="float: right; margin-bottom: 15px"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30]"
          layout="sizes, prev, pager, next, jumper, total"
          :total="+pageTotalCount"
          @size-change="fetchPageListData()"
          @current-change="fetchPageListData()"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { storeToRefs } from 'pinia'
  import useSystemStore from '@/store/main/system/system'
  import { formatUTC } from '@/utils/format'
  import type { IContentConfig } from '.'
  import { usePermission } from '@/hooks/usePermission'

  interface IProp {
    contentConfig: IContentConfig
  }
  /*
    defineProps中类型不能在外部定义，后自动导入，需要在当前文件中书写defineProps类型
      （这是因为vue组件时单独编译的，编译器目前不会抓取导入的文件一分析类型）
  */
  const $props = withDefaults(defineProps<IProp>(), {})
  const $emits = defineEmits(['newClick', 'editClick'])

  const { isCreate, isDelete, isQuery, isUpdate } = usePermission($props.contentConfig.pageName)

  const systemStore = useSystemStore()
  /*
    使用storeToRefs: 将store中的数据转换为响应式数据（如果不转换为响应式数据，在获取到数据发送请求时，
      页面第一次会获取到数据，之后store更新也不会即使响应）
  */
  const { pageList, loading, pageTotalCount, currentPage, pageSize } = storeToRefs(systemStore)

  // 监听systemStore中的actions被执行, 将currentPage重置
  /* systemStore.$onAction(({ name, after }) => {
    // after 在action返回或解决后的钩子
    after(() => {
      if (name === 'deletePageByIdAction' || name === 'editPageDataAction' || name === 'newPageDataAction') {
        currentPage.value = 1
      }
    })
  }) */
  fetchPageListData()

  // 删除操作
  function removeTable(row: any) {
    ElMessageBox.confirm(`是否确定删除${row.name}`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        systemStore.deletePageByIdAction($props.contentConfig.pageName, row.id)
      })
      .catch((err) => ElMessage.error(err!.message))
  }

  // 点击新建部门
  function addDept() {
    $emits('newClick')
  }

  // 编辑部门
  function editTable(row: any) {
    $emits('editClick', row)
  }

  function fetchPageListData(searchForm: any = {}) {
    if (!isQuery.value) return
    const size = pageSize.value
    const offset = (currentPage.value - 1) * size
    const info = { ...searchForm, size, offset }
    systemStore.postPageListAction($props.contentConfig.pageName, info)
  }

  defineExpose({
    fetchPageListData
  })
</script>

<style lang="scss" scoped>
  .content {
    .header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .title {
        font-size: 20px;
      }

      .add-btn {
        margin-left: auto;
      }
    }
    .table {
      .el-table {
        margin-bottom: 15px;
        overflow-y: scroll;
        max-height: 330px;
      }
    }
  }
</style>
